const ws = require("nodejs-websocket");
const { ConnectionMap } = require("./ConnectionMap");
const { onMessage, sendMsg } = require("./message");
const { readData } = require("./data");
const { fileLog } = require("./log");

const port = 12139;
const connectionMap = new ConnectionMap();
global.connectionMap = connectionMap;

fileLog("开始建立连接...");
try {
    ws.createServer(function (connection) {
        const uuid = connectionMap.add(connection);
        if (uuid == null) {
            sendMsg(connection, "connection", false);
            return;
        }

        sendMsg(connection, "connection", true, {
            uuid
        });

        sendMsg(connection, "syncMsgNTF", true, {
            items: readData()
        });

        fileLog("connet", uuid);

        connection.on("text", function (str) {
            fileLog("msg", uuid, str);
            onMessage(connection, str);
        })
        connection.on("close", function () {
            fileLog("close");
            connectionMap.remove(uuid);
        });
        connection.on("error", function (code, reason) {
            fileLog("error", code, reason);
            // connectionMap.remove(uuid);
        });
    }).listen(port);
} catch (e) {
    fileLog("error", e);
}
fileLog("WebSocket建立完毕");

